package wang.yangziqing.app_kotlin.ui.fragment

import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.yan.mobile.player.model.HomeItemBean
import kotlinx.android.synthetic.main.fra_home.*
import wang.yangziqing.app_kotlin.R
import wang.yangziqing.app_kotlin.adapter.HomeAdapter
import wang.yangziqing.app_kotlin.base.BaseFragment
import wang.yangziqing.app_kotlin.model.Homebean
import wang.yangziqing.app_kotlin.net.NetListener
import wang.yangziqing.app_kotlin.net.OkGoUtil
import wang.yangziqing.app_kotlin.utils.URLProviderUtils

/**
 * Created by Administrator on 2017/11/29.
 */
class HomeFragment : BaseFragment() {
    override fun initView(): View? {

        return View.inflate(context, R.layout.fra_home, null)
    }


    val adapter by lazy {

        val list = null
        HomeAdapter(R.layout.item_home, list)
    }

    override fun initListener() {
//初始化 recyclerView
        recyclerView.layoutManager = LinearLayoutManager(context)
        //适配

        recyclerView.adapter = adapter

        adapter.setOnLoadMoreListener(object : BaseQuickAdapter.RequestLoadMoreListener {
            override fun onLoadMoreRequested() {
                loadDatas(adapter.itemCount)

            }
        }, recyclerView)
    }

    override fun initData() {
        loadDatas(1)
    }

    private fun loadDatas(itemCount: Int) {

        val path = URLProviderUtils.getHomeUrl(itemCount, 20);
        println(path)

        val type = object : TypeToken<List<HomeItemBean>>() {}.type
        OkGoUtil.sendPost<List<Homebean>>(path, type, object : NetListener {
            override fun <T> onSuccess(fromJson: T) {
                val list = fromJson as List<HomeItemBean>
                for (l in list) {
                    println(l.title)
                }
                if (list.size < 20) {
                    adapter.addData(list)
                    adapter.loadMoreEnd()
                } else {
                    adapter.addData(list)
                    adapter.loadMoreComplete()
                }
            }
        })


    }


}